/**
 * Static class to wrap layoutSelector methods and values
 */
layoutSelector = (function(){
	var currentlayout = {};
	return{
		/**
		 * Set up click listeners and sortables.
		 */
		init: function(){
			layoutSelector.registerListeners();
			
			jQuery('#customizable_layouts').sortable(
				{
					//axis: 'y',
					revert:true,
					handle: 'h3',
					helper: 'original',
					stop: layoutSelector.updateOrder, // method to be called when order changes
					placeholder: 'hovered'
				}
			);
			
 			jQuery('div#customize_layout_control').find(':input').change(layoutSelector.customize);
		},
		
		/**
		 * Set up click listeners and sortables.  These are the ones that are safe to be called each time a new layout is added.
		 */
		registerListeners: function(){
			jQuery('span.controls a.remove_column').click(layoutSelector.removeColumn);
			jQuery('li.add_sidebars :checkbox').click(layoutSelector.switchColumn);
			jQuery('a.remove_custom_link').click(layoutSelector.removeCustom);
			//jQuery('a.customize_trigger').click(layoutSelector.customize);
			jQuery('.op_layout div.layout_builder').sortable(
				{
					//axis: 'x',
					revert:true,
					handle: '.column_wrap',
					helper: 'original',
					opacity: .70,
					tolerance: 'tolerance',
					placeholder: 'hovered'
					//appendTo: 'body'
				}
			);
			
 			jQuery('.op_layout_wrapper h3').click( function() { jQuery(jQuery(this).parent().get(0)).toggleClass('closed'); } );			
		},
		
		/**
		 * Called by "use sidebar*" checkbox.
		 *
		 * @param e - reference to target element
		 */
		switchColumn: function(e){
			var target = e.srcElement || e.currentTarget, // IE wants us to use srcElement
				useElem = jQuery(target).parents().eq(3).children('.layout_builder'), // Get container for columns layout UI
				toRemove;
			currentlayout.triggeredby = jQuery(target).get(0); // Get the element triggering this function
			currentlayout.elem = jQuery(target).parents('ul.layout_options').next(); // Set element containing columns
			
			// Get current layout identifier, i.e. 'home', 'single', 'category
			currentlayout.layout = jQuery(currentlayout.elem).children().eq(0).children().children().get(2).name.replace(/\[\]/,'');

			// AJAX call to render new column from PHP
			if(currentlayout.triggeredby.checked){ // Add column
				jQuery.ajax({
					type: 'post',
					url: 'admin-ajax.php',
					data: 'action=op_layoutselector_buildcolumn&layout='+currentlayout.layout+'&toid='+currentlayout.triggeredby.value,
					success: layoutSelector.addColumnSuccess
				});
			}
			else{ // Remove column
				useElem.children().each(function(){
					if(this.getAttribute('column').split('_')[1] == currentlayout.triggeredby.value){
						toRemove = this;
					}				
				});
				
				// Remove column UI from canvas when checkbox is unchecked.
				if(toRemove) jQuery(toRemove).remove();				
			}
		},
		
		/**
		 *
		 * Triggered by clicking 'X' in top right of column display
		 *
		 * @param e - reference to target element
		 **/
		removeColumn: function(e){
			// Add confirm?
			
			var target = e.srcElement || e.currentTarget, // IE wants srcElement
				meta = jQuery(target).parents('div.layout_column').get(0).getAttribute('column').split('_'),
				parent = jQuery(target).parents('div.layout_column').get(0),
				checkbox = null;  // init checkbox var
				
			currentlayout.triggeredby = jQuery(target);
			currentlayout.elem = jQuery(target).parents('ul').get(0);
			currentlayout.layout = meta[0]; // figure out layout, i.e. 'home'
			currentlayout.column = meta[1]; // get column id, i.e. 'sidebar1'
			currentlayout.incolumn = (jQuery(currentlayout.elem).children().length) - 1; // how many columns?
		    
			// Go through checkboxes and grab the one that we're removing
			jQuery(parent).parents().eq(1).find('li.add_sidebars ul :input').each(function(){if(this.value==currentlayout.column) checkbox=this});
			checkbox.checked = false; // uncheck corresponding checkbox
			jQuery(parent).remove(); // remove column display
			
			return false; // return false so link doesn't add "#" to url
		},
		
		/**
		 *
		 * switchColumn() AJAX call was successful.  Update UI with HTML from request.
		 *
		 * @param e - reference to target element
		 */
		addColumnSuccess: function(e){			
			var response = e.substring(0,e.length-1); // Clean response.. Wordpress always tacks on a "0" at the end... don't know why
			jQuery(currentlayout.elem).append(response); // Append response to the end of the layout_builder
			
			// set listeners
			layoutSelector.registerListeners();
			
			currentlayout = {};
		},
		
		/**
		 * Customize a layout.  Copy state from default to this layout
		 * @param e - reference to target element
		 */
		customize: function(e){
			var target = e.srcElement || e.currentTarget,
				special, type, fields = [], submenu, main_category;
			
			currentlayout.triggeredby = jQuery(target);
			currentlayout.layout = currentlayout.triggeredby.get(0).value;
			if(currentlayout.triggeredby.get(0).id == ''){
				jQuery('div#customize_layout_control').find(':input').each(function(){if(this.id != ''){jQuery(this).hide()}});

				special = ['tag-name','category-name','page-title'];
				special = ' '+special.join(' ')+' '; // join special options together with whitespace between
				
				// we need to do our check with added whitespace to avoid matching "category" and "tag" as indexOf will find those
				if(special.indexOf(' '+currentlayout.layout+' ') != -1){
					// show secondary drop down box if it's a special
					submenu = jQuery('div#customize_layout_control').find(':input#layout_control_'+currentlayout.layout.split('-')[0]);
					if(jQuery(submenu).children().length > 1)
						submenu.show();
					return;
				} 
				type = '';
			}
			else{
				type = currentlayout.triggeredby.get(0).id.split('_')[2];
			}
			
			jQuery('div#default_layout').find(':input').each(function(){fields.push(this.value)});
			
			jQuery.ajax({
				type: 'post',
				url: 'admin-ajax.php',
				data: 'action=op_layoutselector_customize&layout='+currentlayout.layout+'&default='+fields.join(',')+'&type='+type,
				success: layoutSelector.customizeSuccess
			});
			
			currentlayout.triggeredby.children().each(function(){
				if(this.value == currentlayout.layout){
					if(jQuery(this).parent().children().length == 2){ // if this is the last option in submenu, remove submenu
						jQuery(this).parent().remove();
						main_category = jQuery('#customize_layout_control').find('select').eq(0).val();
						jQuery('#customize_layout_control').find('select').eq(0).children().each(function(){
							if(this.value == main_category) jQuery(this).remove();
						});
					}
					else{ // remove option now that it has been selected
						jQuery(this).remove();	
					}
					
					
				}
			});
			
			
		},
		
		/**
		 * customize() AJAX request was successful
		 *
		 * @param e - reference to target element
		 */
		customizeSuccess: function(e){
			//var container = jQuery(currentlayout.triggeredby).prev();
			var container = jQuery('div#customizable_layouts'),
				response = e.substring(0,e.length-1);  // Clean response.  Get rid of extra "0"

			container.prepend(response);
			container.slideDown('slow'); // show container with new columns inside
			
			// setup listeners
			layoutSelector.registerListeners();
			
			currentlayout = {}; // currentlayout needs to be reset
			
			layoutSelector.updateOrder(); // update the order in case they don't do any drag and dropping
		},
		
		/**
		 * Get rid of customization
		 */
		removeCustom: function(e){
			var target = e.srcElement || e.currentTarget;
			currentlayout.triggeredby = jQuery(target);
			if(confirm('Are you sure you wish to remove all customization for this layout type?')){
				layoutSelector.removeCustomSuccess();
			}
			
			return false;
		},
		
		/**
		 * Remove column display from layout.
		 */
		removeCustomSuccess: function(){
			var container = currentlayout.triggeredby.prev().parents().eq(2),
				select = jQuery('div#customize_layout_control').find('select').eq(0), // add to select again
				options = {},
				layout_id, type, title, uc_option,
				special, k, key, keys, need_to_add, special_type;

			jQuery(container).fadeOut('slow',function(){jQuery(this).remove();});

			layout_id = currentlayout.triggeredby.parent().get(0).id;
			type = layout_id.split('_')[3] ? layout_id.split('_')[2] : '';
			title = layout_id.split('_')[3] ? layout_id.split('_')[3] : layout_id.split('_')[2];

			if(type == ''){
				uc_option = title.toLowerCase().replace(/\w+/g,function(s){ return s.charAt(0).toUpperCase() + s.substr(1); }); // ucwords
				options[title] = uc_option;
			}
			else{
				special = ['tag-name','category-name','page-title'];
				for(var k in special){ // find appropriate option value for special type
					if(special[k].indexOf(type) != -1) special_type = special[k];
				}
				if(special_type){ // if it is a valid type
					need_to_add = true; // whether or not we need to add it to the main customize dropdown
					select.children().each(function(){ // if option already exists, we don't need to add
						if(special_type == this.value) need_to_add = false;
					});
					
					// don't add if there's only 1 option in submenu
					if(need_to_add){ // add special option type back to menu
						uc_option = special_type.replace('-',' ');
						uc_option = uc_option.toLowerCase().replace(/\w+/g,function(s){ return s.charAt(0).toUpperCase() + s.substr(1); }); // ucwords
						options[special_type] = uc_option;
					}
					layoutSelector.regenerateMenu(select,options);
					
					options = {};
					submenu = jQuery('div#customize_layout_control').find(':input#layout_control_'+type).eq(0);
					uc_option = title.replace('-',' ');
					options[title] = uc_option;
					layoutSelector.regenerateMenu(submenu, options);
				}

			}
			
			layoutSelector.regenerateMenu(select,options);

			return false;
		},
		
		regenerateMenu: function(select, options){
			var keys, key;
			
			// Need to figure out which list value belongs to and add it back 
			select.children().each(function(){
				options[this.value] = jQuery(this).text();
			});

			// create an array of keys to sort
			keys = new Array();
			for(key in options){
     			keys.push(key);
			}
			
			// sort the array of keys
			keys.sort();
			select.html('');

			// go through keys in order
			for(key in keys){
				select.append('<option value="'+keys[key]+'">'+options[keys[key]]+'</option>');
			}
		},
		
		/**
		 * User has sorted div's.  Time to store their changes.
		 *
		 */
		updateOrder: function(){
			var layouts = [],
				tmp_id;
			// build array of layout names
			jQuery('#customizable_layouts').children().each(function(){
				tmp_id = jQuery(this).children().eq(1).children().get(0).id.split('_');
				layouts.push(tmp_id[3] && tmp_id[3].length > 0 ? tmp_id[2]+'_'+tmp_id[3] : tmp_id[2]);
			});
			
			// Send AJAX request to have PHP store order of divs
			jQuery.ajax({
				type: 'post',
				url: 'admin-ajax.php',
				data: 'action=op_layoutselector_savestate&layouts='+layouts.join(',')
			});
		}
	}
}());

jQuery(document).ready(layoutSelector.init);